const Highcharts = require("highcharts");
require("highcharts/modules/exporting")(Highcharts);
import round from "lodash/round";
import dayjs from "dayjs";
const formaty = num => round(num / 10000, 1) || 0;
const createFullTime = hour => `2020/01/01 ${hour}`;

const configs = {
  n: {
    ticks: ["10:30", "11:30", "14:00", "15:00"],
    openTime: getOpenTime("09:30", 120).concat(getOpenTime("13:01", 120)) // ["09:00".... "15:00"]
  },
  s: {
    ticks: ["10:00", "11:00", "12:00", "14:00", "15:00"],
    openTime: getOpenTime("09:00", 180).concat(getOpenTime("13:01", 180))
  }
};
/**
 * @param {*} container
 * @param {*} data
 * @param {*} dir - 北向=n/南向=s
 * @param {*} type - 资金流向=flow/余额=balance
 */
export default function draw({ container, data = [], type, dir }) {
  const xMax = data.length - 1; // 最大
  const { ticks, openTime } = configs[dir];
  const tickPositioner = [0];

  const dataByTime = data.reduce((p, c) => {
    const hour = c.tradeDate.match(/[^\s]+$/)[0];
    const time = dayjs(createFullTime(hour)).format("HH:mm");
    p[time] = c;
    return p;
  }, {});

  // 根据时间提取数据
  data = openTime.map((time, i) => {
    const item = dataByTime[time] || {};
    item.x = i;
    item.time = time;
    item.day = item.tradeDate && item.tradeDate.match(/^[^\s]+/)[0];
    if (ticks.includes(time)) {
      tickPositioner.push(i);
    }
    return item;
  });

  const series = getSeries(data, dir)[type];

  const chartOptions = {
    chart: {
      type: "spline",
      marginTop: 40,
      scrollablePlotArea: {
        minWidth: 600,
        scrollPositionX: 1
      }
    },
    exporting: { enabled: false },
    legend: {
      symbolWidth: 5,
      symbolHeight: 5,
      align: "left",
      verticalAlign: "top",
      x: 30,
      y: 0,
      floating: true,
      labelFormatter() {
        return `<span style="color:${this.color}">${this.name}</span>`;
      }
    },
    credits: { enabled: false },
    title: { text: "" },
    xAxis: {
      min: 0,
      max: xMax + 100,
      tickPositioner: () => tickPositioner,
      minorGridLineWidth: 1,
      gridLineWidth: 1,
      startOnTick: true,
      endOnTick: true,
      tickLength: 10,
      tickWidth: 1,
      crosshair: {
        width: 1,
        dashStyle: "Dot"
      },
      labels: {
        align: "center",
        formatter() {
          if (this.value === 0) {
            return data[this.value].day;
          }
          return data[this.value].time;
        }
      }
    },
    yAxis: {
      title: { text: "" },
      minorGridLineWidth: 1,
      gridLineWidth: 1,
      alternateGridColor: null,
      labels: {
        formatter() {
          return formaty(this.value);
        }
      }
    },
    tooltip: {
      valueSuffix: "亿元",
      shared: true,
      formatter: function() {
        return this.points.reduce(function(prev, point) {
          return `${prev}<br/><span style="color:${point.color}">${point.series.name}: ${formaty(point.y)}亿元</span>`;
        }, `<b>${data[this.x].time}</b>`);
      }
    },
    plotOptions: {
      spline: {
        lineWidth: 2,
        states: {
          hover: {
            lineWidth: 2
          }
        },
        marker: {
          enabled: false,
          symbol: "circle"
        },
        pointInterval: 3600000, // one hour
        pointStart: Date.UTC(2018, 1, 13, 0, 0, 0)
      }
    },
    series: series,
    navigation: {
      menuItemStyle: {
        fontSize: "10px"
      }
    }
  };

  Highcharts.chart(container, chartOptions);

  return Highcharts;
}

function getSeries(data, dir) {
  const shFlow = []; // 沪股通-净流入
  const szFlow = []; // 深股通-净流入

  const shBalance = []; // 沪股余额
  const szBalance = []; // 深股余额

  data.forEach(item => {
    shFlow.push({ x: item.x, y: item.hNetFlowIn, time: item.time });
    szFlow.push({ x: item.x, y: item.zNetFlowIn, time: item.time });
    shBalance.push({ x: item.x, y: item.hBalance, time: item.time });
    szBalance.push({ x: item.x, y: item.zBalance, time: item.time });
  });

  const names = {
    n: ["沪股通", "深股通"],
    s: ["港股通(沪)", "港股通(深)"]
  };

  return {
    flow: [
      { name: names[dir][0], data: shFlow, color: "#2C7EFF" },
      { name: names[dir][1], data: szFlow, color: "#FF8A00" }
    ],
    balance: [
      { name: names[dir][0], data: shBalance, color: "#2C7EFF" },
      { name: names[dir][1], data: szBalance, color: "#FF8A00" }
    ]
  };
}

/**
 * 时间区间
 * @param {String} start - 起始时间
 * @param {Number} count - 分钟数
 */
function getOpenTime(start, count) {
  const times = [];
  const beginTime = dayjs(createFullTime(start));
  for (let i = 0; i < count + 1; i++) {
    times.push(beginTime.add(i, "minute").format("HH:mm"));
  }
  return times;
}

/// 主题配置
Highcharts.theme = {
  colors: [
    "#FF8A00",
    "#2C7EFF",
    "#7798BF",
    "#aaeeee",
    "#ff0066",
    "#eeaaee",
    "#55BF3B",
    "#DF5353",
    "#7798BF",
    "#aaeeee"
  ],
  chart: {
    backgroundColor: "#090910",
    plotBorderColor: "#606063"
  },
  xAxis: {
    gridLineColor: "#2C2C30",
    labels: {
      style: {
        color: "#E0E0E3"
      }
    },
    lineColor: "#2C2C30",
    minorGridLineColor: "#505053",
    tickColor: "#2C2C30"
  },
  yAxis: {
    gridLineColor: "#2C2C30",
    labels: {
      style: {
        color: "#E0E0E3"
      }
    },
    lineColor: "#2C2C30",
    minorGridLineColor: "#505053",
    tickColor: "#2C2C30",
    tickWidth: 1
  },
  tooltip: {
    backgroundColor: "rgba(0, 0, 0, 0.85)",
    style: {
      color: "#F0F0F0"
    }
  },
  legend: {
    backgroundColor: "rgba(0, 0, 0, 0)",
    itemStyle: {
      color: "#E0E0E3"
    },
    itemHoverStyle: {
      color: "#FFF"
    },
    itemHiddenStyle: {
      color: "#606063"
    },
    title: {
      style: {
        color: "#C0C0C0"
      }
    }
  },
  plotOptions: {
    series: {
      dataLabels: {
        color: "#F0F0F3",
        style: {
          fontSize: "13px"
        }
      },
      marker: {
        lineColor: "#333"
      }
    },
    boxplot: {
      fillColor: "#505053"
    }
  },
  labels: {
    style: {
      color: "#2C2C30"
    }
  }
};

Highcharts.setOptions(Highcharts.theme);
